package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("regions")
public class RegionController {
    //应用上下文对象的注入 用来获取相对路径
    @Autowired
    private ServletContext servletContext;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @GetMapping
    public List<Region> list(Integer state){
       return regionService.selectAll(state);
    }
    @GetMapping(value = "{regionId}/strategies",produces = "text/html;charset=utf8")
    public void selectStrategyByregionId(StrategyQueryObject qo, HttpServletResponse response) throws Exception {
        //高级查询每页4条 所有攻略信息
        qo.setPageSize(4);
        PageInfo all = strategyService.query(qo);
        //设置攻略状态为推荐状态
        qo.setState(Strategy.STATE_HOT);
        //pageSize为0  并且配置了合理化分页  所有会查询所有推荐的攻略信息
        qo.setPageSize(0);
        PageInfo hot = strategyService.query(qo);
        //FreeMarker:模板+数据模型=视图输出
        //1.chuangjain FreeMarker的核心配置对象
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
        //2.指定模板文件从何处加载数据源,这里设置成一个文件目录
        String path = servletContext.getRealPath("template");//获取文件的相对路径
        configuration.setDirectoryForTemplateLoading(new File(path));
        //3.读取上面设置的文件夹下的指定文件
        configuration.setDefaultEncoding("utf-8");//设置freeMarker配置的默认编码
        Template template = configuration.getTemplate("strategyTemplate.ftl");
        //4.准备数据模型
        Map<String,Object> map = new HashMap<>();
        map.put("all",all);
        map.put("hot",hot);
        //设置编码
        response.setContentType("text/html;charset=UTF-8");
        template.process(map,response.getWriter());
    }

    /**
     * 分页 查询某个地区下的攻略数据
     * @param qo
     * @return
     */
    @GetMapping(value = "{regionId}/strategies",produces = "application/json;charset=utf8")
    public PageInfo selectStrategyByregionId(StrategyQueryObject qo){
        qo.setPageSize(4);
        return strategyService.query(qo);
    }

}
